/**
 * 
 */
package com.cplsystems.incidencias.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cplsystems.incidencias.business.ClavePersonal;
import com.cplsystems.incidencias.business.Persona;
import com.cplsystems.incidencias.dao.ClavePersonalDAO;

/**
 * @author César Palalía López (csr.plz@aisa-automation.com)
 * 
 */
@Repository
public class ClavePersonalDAOImpl extends HibernateDaoSupport implements
		ClavePersonalDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory)
			throws DataAccessException {
		setSessionFactory(sessionFactory);
	}

	@Transactional
	public void save(ClavePersonal clavePersonal) {
		getHibernateTemplate().saveOrUpdate(clavePersonal);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public ClavePersonal getClaveByCEO(Persona responsable) {
		List<ClavePersonal> claves = getHibernateTemplate().find(
				"FROM ClavePersonal as p WHERE p.persona = ?", responsable);
		return claves.size() > 0 ? claves.get(0) : null;
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public ClavePersonal aunthenticate(String usuario, String clave) {
		getHibernateTemplate().find("FROM ClavePersonal as c");
		List<ClavePersonal> claves = getHibernateTemplate()
				.find("FROM ClavePersonal as c "
						+ "LEFT JOIN FETCH c.persona as p "
						+ "WHERE c.usuario = ? AND c.clave = ?", usuario, clave);
		return claves.size() > 0 ? claves.get(0) : null;
	}

}
